package link;

import java.net.*;
import java.io.*;

class Server implements Runnable {

	ReceivedBuffer rb;

	int port;

	public Server(ReceivedBuffer rb, int p) {
		this.rb = rb;
		port = p;
	}

	public void run() {

		DatagramSocket server = null;
		byte[] buf;

		try {
			server = new DatagramSocket(port);
		} catch (IOException e) {
			System.out.println(e);
			System.exit(0); // kill program
		}

		while (true) {
			try {
				buf = new byte[16384];
				DatagramPacket pack = new DatagramPacket(buf, buf.length);
				server.receive(pack);

				// the last two arguments are used to avoid nasty
				// String format under Windows. Huh, so surprising...
				String data = new String(pack.getData(), 0, pack.getLength());

				// if the data is not empty, we enqueue it into
				// the received message buffer
				if (data != null)
					rb.receiveBuffer.addFirst(data);
			} catch (IOException e) {
				System.out.println(e);
				System.exit(0); // kill program
			}
		}
	}
}